export const updateUserStats = (testResults) => {
  const totalTests = testResults.length;
  const avgScore = totalTests > 0
    ? Math.round(testResults.reduce((sum, result) => sum + result.score, 0) / totalTests)
    : 0;

  const level = Math.floor(totalTests / 3) + 1;

  return {
    totalTests,
    averageScore: avgScore,
    level
  };
};

export const checkAchievements = (
  testResults,
  achievements,
  tests,
  testCategories
) => {
  const newAchievements = [...achievements];
  const totalTests = testResults.length;
  const uniqueTestTypes = new Set(testResults.map(r => r.testType)).size;
  const averageScore = totalTests > 0
    ? testResults.reduce((sum, result) => sum + result.score, 0) / totalTests
    : 0;

  // Helper function to unlock achievement
  const unlockAchievement = (id) => {
    const achievement = newAchievements.find(a => a.id === id);
    if (achievement && !achievement.unlocked) {
      achievement.unlocked = true;
      achievement.unlockedDate = new Date();
      return true;
    }
    return false;
  };

  // 基础成就 - 测试完成里程碑
  if (totalTests >= 1) unlockAchievement('first-test');
  if (uniqueTestTypes >= 5) unlockAchievement('five-tests');
  if (uniqueTestTypes >= 10) unlockAchievement('ten-tests');
  if (uniqueTestTypes >= 20) unlockAchievement('twenty-tests');
  if (uniqueTestTypes >= 30) unlockAchievement('all-tests');

  // 表现成就 - 分数相关
  if (testResults.some(r => r.score === 100)) {
    unlockAchievement('perfect-score');
  }
  if (testResults.some(r => r.score >= 95)) {
    unlockAchievement('high-achiever');
  }
  if (averageScore >= 90 && totalTests >= 5) {
    unlockAchievement('average-excellence');
  }

  // 检查连续5个测试85分以上
  const recentResults = testResults.slice(-5);
  if (recentResults.length === 5 && recentResults.every(r => r.score >= 85)) {
    unlockAchievement('consistency-king');
  }

  // 检查完美连击（连续3个测试95分以上）
  const lastThree = testResults.slice(-3);
  if (lastThree.length === 3 && lastThree.every(r => r.score >= 95)) {
    unlockAchievement('perfect-streak');
  }

  // 专业成就 - 按类别计算平均分
  const categoryStats = {};

  testResults.forEach(result => {
    const test = tests.find(t => t.id === result.testType);
    if (test?.category) {
      if (!categoryStats[test.category]) {
        categoryStats[test.category] = {total: 0, sum: 0};
      }
      categoryStats[test.category].total++;
      categoryStats[test.category].sum += result.score;
    }
  });

  // 检查各类别精通成就
  Object.entries(categoryStats).forEach(([category, stats]) => {
    if (stats.total >= 2) {
      const avg = stats.sum / stats.total;

      switch (category) {
        case 'cognitive':
          if (avg >= 85) unlockAchievement('cognitive-master');
          break;
        case 'logical':
          if (avg >= 90) unlockAchievement('logic-genius');
          break;
        case 'creative':
          if (avg >= 85) unlockAchievement('creative-mind');
          break;
        case 'memory':
          if (avg >= 90) unlockAchievement('memory-champion');
          break;
        case 'language':
          if (avg >= 85) unlockAchievement('language-expert');
          break;
        case 'perceptual':
          if (avg >= 85) unlockAchievement('perception-pro');
          break;
        case 'social':
          if (avg >= 90) unlockAchievement('social-intelligence');
          break;
        case 'executive':
          if (avg >= 85) unlockAchievement('executive-excellence');
          break;
        case 'processing':
          if (avg >= 85) unlockAchievement('processing-master');
          break;
        case 'decision':
          if (avg >= 85) unlockAchievement('decision-master');
          break;
        case 'perception':
          if (avg >= 85) unlockAchievement('perception-master');
          break;
      }
    }
  });

  // 坚持成就 - 连续天数
  const streakDays = calculateStreakDays(testResults);
  if (streakDays >= 3) unlockAchievement('streak-3');
  if (streakDays >= 7) unlockAchievement('streak-7');
  if (streakDays >= 14) unlockAchievement('streak-14');
  if (streakDays >= 30) unlockAchievement('streak-30');

  // 综合成就
  const completedCategories = new Set(
    testResults.map(result =>
      tests.find(test => test.id === result.testType)?.category
    ).filter(Boolean)
  );

  if (completedCategories.size >= Object.keys(testCategories).length) {
    unlockAchievement('all-categories');
  }

  // 全面发展 - 每个类别都80分以上
  const allCategoriesGood = Object.keys(testCategories).every(category => {
    const stats = categoryStats[category];
    return stats && stats.total >= 1 && (stats.sum / stats.total) >= 80;
  });
  if (allCategoriesGood && Object.keys(categoryStats).length >= 8) {
    unlockAchievement('well-rounded');
  }

  // 认知精英 - 所有测试90分以上
  if (totalTests >= 10 && averageScore >= 90) {
    unlockAchievement('cognitive-elite');
  }

  // 认知至尊 - 所有类别都达到专精
  const masteryCategories = Object.keys(testCategories);
  const allCategoriesMastery = masteryCategories.every(category => {
    const stats = categoryStats[category];
    return stats && stats.total >= 2 && (stats.sum / stats.total) >= 85;
  });
  if (allCategoriesMastery && Object.keys(categoryStats).length >= masteryCategories.length) {
    unlockAchievement('cognitive-supreme');
  }

  // 终极学者 - 完成所有测试且平均分95+
  if (uniqueTestTypes >= 30 && averageScore >= 95) {
    unlockAchievement('ultimate-scholar');
  }

  // 进步大师 - 同一测试提高20分
  const testProgressions = {};
  testResults.forEach(result => {
    const testType = result.testType;
    if (!testProgressions[testType]) {
      testProgressions[testType] = [];
    }
    testProgressions[testType].push(result.score);
  });

  Object.values(testProgressions).forEach(scores => {
    if (scores.length >= 2) {
      const min = Math.min(...scores);
      const max = Math.max(...scores);
      if (max - min >= 20) {
        unlockAchievement('improvement-master');
      }
    }
  });

  // 时间相关成就
  const now = new Date();
  const recentTests = testResults.filter(r => {
    const resultTime = new Date(r.completedAt || r.date || r.timestamp || new Date());
    const hoursDiff = Math.abs(now.getTime() - resultTime.getTime()) / (1000 * 60 * 60);
    return hoursDiff <= 24;
  });

  recentTests.forEach(result => {
    const testTime = new Date(result.completedAt || result.date || result.timestamp || new Date());
    const hour = testTime.getHours();

    if (hour >= 22 || hour <= 6) {
      unlockAchievement('night-owl');
    }
    if (hour >= 5 && hour <= 7) {
      unlockAchievement('early-bird');
    }
  });

  // 专项测试成就
  testResults.forEach(result => {
    const testType = result.testType;

    switch (testType) {
      case 'reaction':
        if (result.details?.averageTime && result.details.averageTime < 200) {
          unlockAchievement('reaction-lightning');
        }
        if (result.score >= 95) {
          unlockAchievement('speed-demon');
        }
        break;

      case 'typing':
        if (result.score >= 90) {
          unlockAchievement('typing-master');
        }
        break;

      case 'math':
        if (result.score === 100 && result.duration && result.duration < 180) {
          unlockAchievement('math-wizard');
        }
        if (result.score >= 95 && result.duration && result.duration < 240) {
          unlockAchievement('quick-thinker');
        }
        break;

      case 'memory':
        if (result.details?.itemsRemembered && result.details.itemsRemembered >= 15) {
          unlockAchievement('memory-palace');
        }
        break;

      case 'visual':
        if (result.score === 100) {
          unlockAchievement('eagle-eye');
        }
        break;

      case 'color':
        if (result.score >= 95) {
          unlockAchievement('color-master');
        }
        break;

      case 'coordination':
        if (result.score === 100) {
          unlockAchievement('coordination-king');
        }
        break;

      // 新增测试的专项成就
      case 'digit-memory':
        if (result.details?.workingMemorySpan && result.details.workingMemorySpan >= 5) {
          unlockAchievement('digit-savant');
        }
        break;

      case 'time-perception':
        if (result.details?.averageError && result.details.averageError <= 5) {
          unlockAchievement('time-master');
        }
        break;

      case 'concept-formation':
        if (result.score >= 95 && result.duration && result.duration < 300) {
          unlockAchievement('concept-genius');
        }
        break;

      case 'spatial-memory':
        if (result.score === 100) {
          unlockAchievement('spatial-navigator');
        }
        break;

      case 'verbal-fluency':
        if (result.details?.totalWords && result.details.totalWords >= 50) {
          unlockAchievement('verbal-virtuoso');
        }
        break;

      case 'decision-making':
        if (result.score >= 90) {
          unlockAchievement('decision-maker');
        }
        break;

      case 'processing-speed':
        if (result.score >= 95 && result.duration && result.duration < 120) {
          unlockAchievement('processing-pro');
        }
        break;
    }
  });

  // 隐藏成就
  // 幸运七 - 第7次测试获得77分
  if (testResults.length >= 7 && testResults[6]?.score === 77) {
    unlockAchievement('lucky-seven');
  }

  // 百分俱乐部 - 100次测试
  if (totalTests >= 100) {
    unlockAchievement('century-club');
  }

  // 完美主义者 - 5个不同测试都满分
  const perfectTests = testResults.filter(r => r.score === 100).map(r => r.testType);
  const uniquePerfectTests = new Set(perfectTests);
  if (uniquePerfectTests.size >= 5) {
    unlockAchievement('perfectionist');
  }

  // 文艺复兴思维 - 在艺术、科学、语言测试中都表现卓越
  const renaissanceCategories = ['creative', 'academic', 'language'];
  const renaissanceGood = renaissanceCategories.every(category => {
    const stats = categoryStats[category];
    return stats && stats.total >= 1 && (stats.sum / stats.total) >= 85;
  });
  if (renaissanceGood) {
    unlockAchievement('renaissance-mind');
  }

  // AI对战成就
  const aiBattleResults = testResults.filter(r => r.details?.battleMode);
  if (aiBattleResults.length >= 1) {
    unlockAchievement('ai-challenger');
  }

  const aiWins = aiBattleResults.filter(r => r.details?.winner === 'player');
  if (aiWins.length >= 1) {
    unlockAchievement('ai-victor');
  }

  // 检查连续3次AI对战胜利
  const recentAiBattles = aiBattleResults.slice(-3);
  if (recentAiBattles.length === 3 && recentAiBattles.every(r => r.details?.winner === 'player')) {
    unlockAchievement('ai-dominator');
  }

  return newAchievements;
};

export const calculateStreakDays = (testResults) => {
  if (testResults.length === 0) return 0;

  // 按日期分组测试结果
  const testsByDate = new Map();
  testResults.forEach(result => {
    const resultDate = new Date(result.completedAt || result.date || result.timestamp || new Date());
    const dateString = resultDate.toDateString();
    if (!testsByDate.has(dateString)) {
      testsByDate.set(dateString, []);
    }
    testsByDate.get(dateString).push(result);
  });

  // 获取有测试的所有日期并排序
  const testDates = Array.from(testsByDate.keys())
    .map(dateString => new Date(dateString))
    .sort((a, b) => b.getTime() - a.getTime()); // 从最近到最远排序

  if (testDates.length === 0) return 0;

  const today = new Date();
  today.setHours(0, 0, 0, 0);

  let streak = 0;
  let currentDate = new Date(today);

  // 从今天开始往前检查连续天数
  for (let i = 0; i < 30; i++) { // 最多检查30天
    const currentDateString = currentDate.toDateString();
    const hasTestOnDay = testDates.some(date => date.toDateString() === currentDateString);

    if (hasTestOnDay) {
      streak++;
    } else if (i === 0) {
      // 如果今天没有测试，检查昨天
      currentDate.setDate(currentDate.getDate() - 1);
      continue;
    } else {
      // 连续性中断
      break;
    }

    currentDate.setDate(currentDate.getDate() - 1);
  }

  return streak;
};